const Lables = require('../model/lables.js');
const articleAndLable = require('../model/articleAndLable.js');
const article = require('../model/article');
const {
    returnarticle
}=require("./article.js")
const { Op } = require("sequelize");
class Lable {
    /* 分页获取标签 */
    async getLableInfo(pageIndex,pageSize) {
       try {
        let res = await Lables.findAll({
            offset: (pageIndex-1) * pageSize,
            limit: parseInt(pageSize)
        })
        let data = res.map((item)=>{
            return item.dataValues
        })
        return {
            code:1,
            data,
            msg:'获取成功'
        }
       } catch (error) {
        console.log(error);
        return {
            code:0,
            msg:'获取失败'
        }
       }
    }
    /* 编辑标签 */
    async editlable(lable_name,lable_id) {
        let res = await Lables.update({ lable_name:lable_name },{
            where: {
                id: lable_id
            }
        })
        if(res[0] != 0){
            return {
                code:1,
                msg:'编辑成功'
            }
        }else{
            return {
                code:0,
                msg:'编辑失败'
            }
        }
    }
    /* 删除单个标签 
    改变this指向 因为在类里面是代码严格模式this为未定义,
    箭头函数的this指向它定义的作用域,这里是类*/
    deletelable =async (lable_id)=> {
        let isdata =await this.getonelable(null,lable_id)
        if(isdata.code){
            /* 查询标签绑定的文章 */
            let isarticle =await articleAndLable.count({where: {lable_id}})
            if(isarticle!=0){
                return {
                    code:0,
                    msg:'该标签下有文章，不能删除'
                }
            }else{
              let xx = await Lables.destroy({
                where: {
                    id:lable_id
                }
            })
              if(xx>0){
                return {
                    code:1,
                    msg:'删除成功'
                }
              }else{
                return {
                    code:0,
                    msg:'删除失败'
                }
              }
            }
        }else{
            return {
                code:0,
                msg:'该标签不存在'
            }
        }
    }
    /* 模糊匹配标签搜索 */
    async searchlables(lable_name, pageinfo) {
        const whereOpt = {}
        lable_name &&
            Object.assign(whereOpt, {
                lable_name: {
                    [Op.like]: `%${lable_name}%`,
                },
            })
        let num = await Lables.count({
            where:whereOpt,
        })
        if (num==0) {
            return {
                code: 0,
                msg: '没有该标签'
            }
        } else {
            let { pageIndex, pageSize } = JSON.parse(JSON.stringify(pageinfo));
            let lablelist = await Lables.findAll({
                where: whereOpt,
                limit: pageSize,
                offset: (pageIndex - 1) * pageSize
            })
            let data = lablelist.map((item)=>{
                return item.dataValues
            })
            return {
                code:1,
                data,
                num,
                msg:'获取成功'
            }
        }
    }
    /* 添加标签 */
    async addlable(lable_name) {
        let lable = await Lables.create({ lable_name })
        if (lable) {
            return {
                code: 1,
                msg: '添加成功',
                data: lable.dataValues
            }
        } else {
            return {
                code: 0,
                msg: '添加失败',
                data: null
            }
        }
    }
    /* 获取单个标签根据标签名字或者id */
    async getonelable(lable_name=null,lable_id=null) {
        let lable
        if(lable_name){
            lable=await Lables.findOne({ where: { lable_name } });
        }else{  
            lable_id = parseInt(lable_id);
            lable = await Lables.findOne({ where: { id:lable_id } });
        }
        if (lable) {
            return {
                code: 1,
                msg: '获取成功',
                data: lable.dataValues
            };
        } else {
            return {
                code: 0,
                msg: '获取标签失败',
                data: {}
            };
        }
    }
    /* 获取标签的数量 */
    async getcount(){
       let count=await Lables.count();
       console.log(count);
       return {
            code:1,
            msg:'获取成功',
            data:count
       };
    }
    /* 批量删除 */
    deleteAllLable = async (deleteList)=>{
        let reslist=deleteList.map(async item => {
            let res = await this.deletelable(item)
            return res
        })
        let ress=await Promise.all(reslist) 
        return ress
    }
    /* 一次性获取全部标签 */
    async getAllLable(){
        let lablelist=await Lables.findAll({
            attributes:["id","lable_name"]
        })
        let res=lablelist.map(item=>item.dataValues)
        return {
            code:1,
            msg:'获取成功',
            data:res
        };
    }
    async ServerSelectlable(lable_id,page,pageSize){
        if (page == null || pageSize == null) {
            return {
              code: 0,
              msg: '参数错误'
            }
          }
          page = (typeof page == "string") ? parseInt(page) : page;
          pageSize = (typeof pageSize == "string") ? parseInt(pageSize) : pageSize;
        let count = await articleAndLable.count({
            
            where:{
                lable_id
            }
        })
        let lable = await articleAndLable.findAll({
            limit:pageSize,
            offset:(page-1)*pageSize,
            attributes:["article_id"],
            where:{
                lable_id
            }
        })
        lable = lable.map(item=>item.dataValues.article_id)
        if(lable.length>0){
            let res = await article.findAll({
                where:{
                    id:{
                        [Op.in]:lable
                    }
                }
            })
            let ress = await returnarticle(res)
            return {
                code:1,
                msg:'获取成功',
                data:{
                    articlelist:ress,
                    count:count
                },
            }
        }else{
            return {
              code:0,
              msg:'暂无文章',
              data:{
                  articlelist:[],
                  count:0
              }
            }
        }
        
    }
}

module.exports = new Lable();
